<template>
    <div class="groupManage-container">
        <ZWGroup ref="groupList" :type="21" :group-id="group_id" :auth-code="authCode" @submit="handleGroupSubmit" />
        <div class="right_box">
            <div class="gc-header">
                <ZwSearchForm
                    row-num="3"
                    :option="searchOption"
                    @search="search"
                    @reset="reset"
                    @expand="expandHandle" />
            </div>
            <ZwTable
                ref="tableRef"
                class="table-box"
                :tab-h="`calc(100vh - 294px - ${state.searchHeight})`"
                :option="tableOption"
                :fetch-params="state.searchParams"
                :fetch-api="fetchApi()"
                :close-loading="true"
                @select-all="onSelectAll"
                @select="onSelect">
                <template #headerOperate>
                    <el-button v-auth="'ADD_PULL_GROUP'" type="primary" @click="handleAdd"> 新建拉群 </el-button>
                </template>
            </ZwTable>
        </div>
        <!-- 客户明细 -->
        <StaffInfo ref="StaffInfoRef" :details-id="rowId" />
        <!-- 删除弹框 -->
        <ZWDeletdialog ref="ZWDeletdialogRef" @submit="confirmDel" />
    </div>
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'AUTO_PULL_GROUP' });
</script>

<script lang="tsx" setup>
import { reactive, ref, onMounted, onActivated, computed, nextTick } from 'vue';
import StaffInfo from './components/staffInfo.vue';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import ZWGroup from '@/components/ZWGroup.vue';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import { ElMessage, ElImage, ElPopover, ElIcon, ElButton } from 'element-plus';
import { customerRemove, getAutoGroupList, customerDownload } from '@/api/customerCenter/autoPullGroup';
import { Picture as IconPicture } from '@element-plus/icons-vue';
import router from '@/router';
import { useStore } from '@/store';
import { deepCopy } from '@/utils/helper';
import { div } from '@/utils/math';
import { endLoading, startLoading } from '@/utils/request';
import { isCachePage } from '@/utils/utils';
import { useRoute } from 'vue-router';

const route = useRoute();
const store = useStore();
const StaffInfoRef = ref(null);
const ZWDeletdialogRef = ref(null);
const removeId = ref(0);
const rowId = ref();

const tableRef = ref();
const groupList = ref();
const group_id = ref<string>('all');

const requestFlag = ref<boolean>(false);
const currentParams = ref<any>(null);

const searchOption = computed(() => {
    return [
        {
            label: '群名称',
            name: 'name',
            value: '',
            type: 'input',
            placeholder: '请输入群名称'
        },
        {
            label: '拉群方式',
            name: 'group_type',
            value: '',
            type: 'select',
            placeholder: '请选择拉群方式',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve([
                        { name: '全部', id: '0' },
                        { name: '群二维码', id: '1' },
                        { name: '企微活码', id: '2' }
                    ]);
                });
            },
            formatOption: (v: { name: any; id: any }) => ({
                label: v.name,
                value: v.id
            })
        },

        {
            label: '创建时间',
            name: 'create_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
        }
    ];
});
const tableOption = [
    {
        prop: 'name',
        label: '群名称',
        width: 200,
        showOverflowTooltip: true
    },
    {
        label: '二维码',
        minWidth: 200,
        render({ row }: any) {
            const slotError = () => (
                <div class="image_slot">
                    <ElIcon>
                        <IconPicture />
                    </ElIcon>
                </div>
            );
            return (
                <div class="cusInfo">
                    <ElImage
                        preview-src-list={[row.qr_code_link]}
                        preview-teleported={true}
                        vSlots={{ error: slotError }}
                        src={row.qr_code_link}
                        fit="cover"
                        class="avatar"
                        style={{ width: '100px' }}></ElImage>
                </div>
            );
        }
    },
    {
        label: '使用群/群活码',
        width: 300,
        render({ row }: any) {
            const slotReference = () => (
                <div vShow={row.groupchat?.length > 1}>
                    {row.groupchat &&
                        row.groupchat.map((item: any, index: number) => {
                            if (index <= 1) {
                                return (
                                    <p class="ewm_box">
                                        <span class="grop_name" title={item.name}>
                                            {item.name}
                                        </span>
                                        <span>（{item.member_nums}人）</span>
                                        <span
                                            style={{
                                                color:
                                                    item.status_name == '拉人中'
                                                        ? '#59D2A0'
                                                        : item.status_name == '已拉满'
                                                        ? '#FE292B'
                                                        : ''
                                            }}>
                                            {item.status_name}
                                        </span>
                                    </p>
                                );
                            }
                        })}
                </div>
            );
            const slotDefault = () => (
                <el-scrollbar max-height="100px">
                    <div vShow={row.groupchat?.length > 1}>
                        {row.groupchat &&
                            row.groupchat.map((item: any, index: number) => {
                                return (
                                    <div class="ewm_box" style={{ display: 'flex' }}>
                                        <div
                                            class="grop_name"
                                            style={{
                                                overflow: 'hidden',
                                                width: '100px',
                                                'white-space': 'nowrap',
                                                'text-overflow': 'ellipsis'
                                            }}
                                            title={item.name}>
                                            {item.name}
                                        </div>
                                        <div>（{item.member_nums}人）</div>
                                        <div
                                            style={{
                                                color:
                                                    item.status_name == '拉人中'
                                                        ? '#59D2A0'
                                                        : item.status_name == '已拉满'
                                                        ? '#FE292B'
                                                        : ''
                                            }}>
                                            {item.status_name}
                                        </div>
                                    </div>
                                );
                            })}
                    </div>
                </el-scrollbar>
            );
            return (
                <>
                    <ElPopover
                        popper-class="popGroup"
                        trigger="hover"
                        vSlots={{ reference: slotReference, default: slotDefault }}
                        width={'auto'}
                        popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"></ElPopover>
                    <div vShow={row.groupchat.length < 2}>
                        {row.groupchat &&
                            row.groupchat.map((item: any, index: number) => {
                                return (
                                    <p class="ewm_box">
                                        <span
                                            class="grop_name"
                                            style={{
                                                display: 'inline-block',
                                                overflow: 'hidden',
                                                'white-space': 'nowrap',
                                                'text-overflow': 'ellipsis'
                                            }}
                                            title={item.name}>
                                            {item.name}
                                        </span>
                                        <span>（{item.member_nums}人）</span>
                                        <span
                                            style={{
                                                color:
                                                    item.status_name == '拉人中'
                                                        ? '#59D2A0'
                                                        : item.status_name == '已拉满'
                                                        ? '#FE292B'
                                                        : ''
                                            }}>
                                            {item.status_name}
                                        </span>
                                    </p>
                                );
                            })}
                    </div>
                    <p vShow={row.groupchat.length == 0}>--</p>
                </>
            );
        }
    },
    {
        label: '客户情况',
        minWidth: 200,
        render({ row }: any) {
            return (
                <>
                    <div vShow={row.customer}>
                        <div>添加客户 {row.customer.add} 人</div>
                        <div>已入群客户 {row.customer.join} 人</div>
                        <div>已退群客户 {row.customer.quit} 人</div>
                    </div>
                    <span vShow={!row.customer}></span>
                </>
            );
        }
    },
    {
        prop: 'group',
        label: '所属分组',
        minWidth: 200
    },
    {
        prop: 'group_type_name',
        label: '拉群方式',
        minWidth: 200
    },
    {
        prop: 'created_at',
        label: '创建时间',
        minWidth: 200
    },
    {
        prop: 'operate',
        label: '操作',
        width: 300,
        fixed: 'right',
        isOperate: true,
        option: [
            {
                name: '客户明细',
                authCode: 'VIEW_CUSTOMER_DETAIL',
                click: (row: any, index: number) => handleDetails(index, row)
            },
            { name: '查看', authCode: 'VIEW', click: (row: any, index: any) => handleLook(index, row) },
            { name: '编辑', authCode: 'EDIT', click: (row: any, index: number) => handleEdit(index, row) },
            { name: '下载', authCode: 'DOWNLOAD', click: (row: any, index: number) => handleDown(index, row) },
            { name: '删除', authCode: 'DEL', click: (row: any, index: number) => handleDel(index, row) }
        ]
    }
    // {
    //   prop: 'operate',
    //   label: '操作',
    //   fixed: 'right',
    //   width: 250,
    //   isOperate: true,
    //   render({ row }: any) {
    //     return (
    //       <div class="handle">
    //         <ElButton class="btn_opc" size="small" onClick={() => handleDetails(index, row)} vAuth={'VIEW_CUSTOMER_DETAIL'}>
    //           客户明细
    //         </ElButton>
    //         <ElButton class="btn_opc" size="small" onClick={() => handleLook(index, row)} vAuth={'VIEW'}>
    //           查看
    //         </ElButton>
    //         <ElButton class="btn_opc" size="small" onClick={() => handleEdit(index, row)} vAuth={'EDIT'}>
    //           编辑
    //         </ElButton>
    //         <ElButton class="btn_opc" size="small" onClick={() => handleDown(index, row)} vAuth={'DOWNLOAD'}>
    //           下载
    //         </ElButton>
    //         <ElButton class="btn_opc" size="small" onClick={() => handleDel(index, row)} vAuth={'DEL'}>
    //           删除
    //         </ElButton>
    //       </div>
    //     )
    //   }
    // }
];
const defaultParams = reactive({
    name: '',
    group_type: '0',
    create_time: [],
    group_id: 'all'
});
const state = reactive({
    searchParams: deepCopy(defaultParams),
    searchHeight: '112px'
});
const search = (data: any) => {
    currentParams.value = { ...deepCopy(defaultParams), ...data, group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
};
const reset = (v?: any) => {
    currentParams.value = { ...deepCopy(defaultParams), group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
};
/**
 * @description: 展开收起
 */
const expandHandle = (expand: boolean) => {
    state.searchHeight = expand ? '112px' : '64px';
};
const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH();
    });
};
// 选中表格 checkbox
const onSelect = (selection: any) => {
    // selectId.value = getSetionId('id', selection)
};
// 全选
const onSelectAll = (selection: any) => {
    // selectId.value = getSetionId('id', selection)
};
const fetchApi = () => {
    // 获取文件列表
    getTableH();
    return getAutoGroupList;
};

const authCode = {
    add: 'ADD_SUBGROUP',
    edit: 'EDIT_SUBGROUP',
    del: 'DEL_SUBGROUP'
};

const handleGroupSubmit = (data: any) => {
    // 解决切换分组，点击新增然后取消之后的默认分组问题 ⬇️
    router.push({ path: '/customer/groupManage/autopullgroup', query: { group_id: data.id } });
    group_id.value = data.id;
    currentParams.value = { ...deepCopy(defaultParams), ...currentParams.value, group_id: group_id.value };
    state.searchParams = deepCopy(currentParams.value);
};
const handleDetails = (index: number, row: any) => {
    removeId.value = row.id;
    StaffInfoRef.value.appDialog.visible = true;
    StaffInfoRef.value.id = row.id;
    rowId.value = row.id;
    StaffInfoRef.value.appDialog.title = `【${row.name}】客户明细`;
};
// 下载
const handleDown = async (index: number, row: any) => {
    const res = await customerDownload({
        id: [row.id]
    });
    window.open(res.url);
};
// 删除
const handleDel = (index: number, row: any) => {
    ZWDeletdialogRef.value.appDialog.visible = true;
    ZWDeletdialogRef.value.content = '确定删除吗';
    removeId.value = row.id;
};
// 确定删除
const confirmDel = async () => {
    startLoading();
    try {
        const res = await customerRemove({
            id: [removeId.value]
        });
        ElMessage.success('删除成功');
        ZWDeletdialogRef.value.appDialog.visible = false;
        await groupList.value.getGroup(21);
        tableRef.value.reload();
    } catch (error) {
        endLoading();
    }
};

// 新建自动拉群
const handleAdd = () => {
    router.push({
        path: '/customer/groupManage/autopullgroup/creategroupchat',
        query: { group_id: group_id.value == 'all' ? '0' : group_id.value }
    });
};
// 查看
const handleLook = (index: number, row: any) => {
    router.push('/customer/groupManage/autopullgroup/creategroupchat?look=true&id=' + row.id + '&type=look');
};
// 编辑
const handleEdit = (index: number, row: any) => {
    router.push('/customer/groupManage/autopullgroup/creategroupchat?isEdit=true&id=' + row.id + '&type=edit');
};

onActivated(async (val: any) => {
    const groupId = Number(route.params?.group_id || route.query?.group_id);
    if (isCachePage() || groupId || groupId == 0) {
        if ((groupId || groupId == 0) && group_id.value != groupId) {
            group_id.value = groupId;
        } else {
            await groupList.value.getGroup(21);
        }
        groupList.value.setCurrentSelectId({ id: group_id.value });
        state.searchParams = {
            ...deepCopy(defaultParams),
            ...currentParams.value,
            group_id: groupId || group_id.value
        };
    }
});
</script>

<style scoped lang="scss">
:deep(.grop_name) {
    display: inline-block;
    width: 100px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.groupManage-container {
    display: flex;

    .right_box {
        flex: 1;
        height: calc(100vh - 142px);
        padding: 24px;
        border: 1px solid #eaeaea;
        border-radius: 4px;
        box-sizing: border-box;
        background-color: #fff;
        display: flex;
        flex-direction: column;
        overflow: hidden;

        .zw-table {
            display: flex;
            flex-direction: column;
            flex: 1;
            overflow: hidden;

            :deep(.el-table) {
                flex: 1;

                .el-table__empty-block {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                }
            }
        }
    }

    :deep(.ewm_box) {
        span {
            vertical-align: middle;
        }
    }
}

:deep(.btn_opc) {
    margin: 0 6px;
}

:deep(.btn_opc:nth-child(-n + 3)) {
    margin-bottom: 8px;
}

.gc-header {
    margin-bottom: 20px;
    background-color: #f9f9f9;

    .form-inline {
        justify-content: space-between;

        .el-form-item {
            margin-bottom: 0;
            padding: 18px;
        }

        display: flex;
        align-items: center;
    }
}

.btn-wrap {
    display: flex;
}

.zw_table {
    margin: 0;
}

.gc-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 18px 18px;
    font-size: 14px;
    color: #33302d;
}

.customer_tooltip {
    padding: 0 12px;

    h4,
    div {
        display: inline-block;
        line-height: 20px;
        color: #33302d;
    }

    > h4 {
        width: 80px;
        text-align: left;
    }
}

.handle-box {
    padding-bottom: 16px;
    text-align: right;
}
</style>
